  <template>
    <div class="asset-correlation-page">
      <div>
        <van-nav-bar title="关联资产" @click-left="onClickLeft" left-arrow />
      </div>

      <div class="search-section">
        <vsearch 
          placeholder="请输入资产名称"
          :showicon="true"
          @search="onSearch"
          @input="onSearchInput"
          @openpopup="openFilter"
        />
      </div>

      <div class="asset-list">
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          :immediate-check="false"
        >
          <div 
            v-for="(item, index) in assets" 
            :key="item.id || index" 
            class="asset-item"
            @click="selectAsset(item)"
          >
            <van-radio 
              :name="item.id" 
              v-model="selectedId" 
              :value="item.id"
              checked-color="#3772ff"
              class="asset-radio"
            ></van-radio>
            
            <van-image
              :src="item.image"
              width="80"
              height="80"
              fit="cover"
              class="asset-image"
            >
              <template #error>
                <div class="image-error">
                  <van-icon name="photo-fail" size="30" color="#ccc" />
                </div>
              </template>
            </van-image>
            
            <div class="asset-info">
              <div class="asset-title">{{ item.name }}</div>
              <div class="asset-address" v-if="item.address && item.address !== '--'">地址:{{ item.address }}</div>
              <div class="asset-category">{{ item.category }} | {{ item.usage }}</div>
              <div class="asset-statistics">{{ item.statName }}:{{ item.statValue }}{{ item.statUnit }}</div>
            </div>
          </div>
        </van-list>
      </div>
       <div class="btn-container">
            <div class="btnlist">
                <div class="btn-item" :class="{ activeBtn: type === 1 }" @click="closeBtn">重置</div>
                <div class="btn-item" :class="{ activeBtn2: type === 2 }" @click="submitBtn">确认</div>
            </div>
        </div>
    </div>
  </template>
  <script>
  import vsearch from './components/vsearch.vue'
  import backMixin from '../../mixins/backMixin'

    export default {
      mixins: [backMixin],
      components: {
        vsearch
      },
    data() {
      return {
         type: 1,
        searchVal: '',
        selectedId: null,
        assets: [],
        loading: false,
        finished: false,
        pageNum: 1,
        pageSize: 20
      }
    },
    computed: {
      
    },
    mounted(){
      // 手动触发初始加载
      this.onLoad()
    },
    methods: {
      onLoad() {
        // 下拉加载更多
        this.getpropertyList()
      },
      // 格式化资产数据
      formatAssetData(item) {
        const businessDto = item.businessDto || {}
        
        // 提取资产图片（belongType === 2 的附件）
        let image = ''
        if (businessDto.attachmentWebDtoList && businessDto.attachmentWebDtoList.length > 0) {
          const imageAttachment = businessDto.attachmentWebDtoList.find(att => att.belongType === 2)
          if (imageAttachment && imageAttachment.attachData) {
            try {
              const attachData = JSON.parse(imageAttachment.attachData)
              if (attachData && attachData.length > 0 && attachData[0].fileUrl) {
                image = attachData[0].fileUrl
              }
            } catch (e) {
              console.error('解析附件数据失败:', e)
            }
          }
        }
        
        return {
          id: businessDto.id,
          name: businessDto.name || '--',
          address: businessDto.address || businessDto.coordinateAddress || '--',
          category: businessDto.typeName || '--',
          usage: businessDto.purposeNames || '--',
          statName: businessDto.countAmountName || '--',
          statValue: businessDto.countAmount !== null && businessDto.countAmount !== undefined ? businessDto.countAmount : '--',
          statUnit: businessDto.countUnit || '',
          image: image,
          // 保留原始数据，方便后续使用
          businessDto: businessDto
        }
      },
      async getpropertyList(){
        try {
          const data = {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            query: {
              states: [1],
              typeIds: [],
              currentNode: 0,
              keywords: this.searchVal || "",
              auditStates: [],
              orgId: "100008",
              projectIds: [],
              projectNodeIds: [],
              excludeInPlan: 1,
              rightUnitIds: [],
              softStates: [0, 4]
            }
          }

          this.loading = true
          const res = await this.$Posting(this.$api.getpropertyList, data)
          console.log(res, 'getpropertyList res')
          
          if (res.code === '0' && res.data) {
            const rawList = res.data.list || []
            if (rawList.length > 0) {
              // 格式化数据并追加到现有列表
              const formattedAssets = rawList.map(item => this.formatAssetData(item))
              this.assets = [...this.assets, ...formattedAssets]
              this.pageNum++
              this.loading = false
              
              // 判断是否还有更多数据
              if (!res.data.hasNextPage) {
                this.finished = true
              }
            } else {
              // 没有更多数据了
              this.loading = false
              this.finished = true
            }
          } else {
            this.loading = false
            this.finished = true
            if (res.message) {
              this.$toast(res.message)
            }
          }
        } catch (error) {
          console.error('加载数据失败:', error)
          this.loading = false
          this.finished = true
          this.$toast('加载失败，请重试')
        }
      },

      onClickLeft() {
        this.$router.back()
      },
       closeBtn() {
        this.getpropertyList()
       },
        submitBtn() {
          
        },
      onSearch(value) {
        this.searchVal = value
        this.resetAndLoad()
      },
      onSearchInput(value) {
        this.searchVal = value
        // 输入时也可以实时搜索，或者只在搜索按钮点击时搜索
        // 这里可以根据需求决定是否实时搜索
      },
      resetAndLoad() {
        // 重置分页状态并重新加载
        this.pageNum = 1
        this.assets = []
        this.finished = false
        this.loading = false
        // 触发加载
        this.onLoad()
      },
      selectAsset(asset) {
        this.selectedId = asset.id
      },
      openFilter() {
        // 打开筛选弹窗
        console.log('打开筛选')
      }
    }
  }
  </script>
    

  <style scoped>
  .asset-correlation-page {
    background-color: #fff;
    min-height: 100vh;
  }

  .search-section {
    width: 100%;
    padding: 10px 15px;
    background-color: #fff;
    box-sizing: border-box;
  }

  .asset-list {
    background-color: #fff;
    padding: 0;
  }

  .asset-item {
    display: flex;
    align-items: flex-start;
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    background-color: #fff;
  }

  .asset-item:last-child {
    border-bottom: none;
  }

  .asset-item:active {
    background-color: #f9f9f9;
  }

  .asset-radio {
    margin-right: 12px;
    margin-top: 4px;
    flex-shrink: 0;
  }

  .asset-image {
    flex-shrink: 0;
    margin-right: 12px;
    border-radius: 4px;
    overflow: hidden;
    border: 1px solid #e0e0e0;
  }

  .image-error {
    width: 80px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f5f5;
    border-radius: 4px;
  }

  .asset-info {
    flex: 1;
    min-width: 0;
  }

  .asset-title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin-bottom: 6px;
    line-height: 1.4;
  }

  .asset-address {
    font-size: 13px;
    color: #666;
    margin-bottom: 6px;
    line-height: 1.4;
  }

  .asset-category {
    font-size: 13px;
    color: #666;
    margin-bottom: 6px;
    line-height: 1.4;
  }

  .asset-statistics {
    font-size: 13px;
    color: #666;
    line-height: 1.4;
  }
   .btn-container {
        position: absolute;
        bottom: 100px;
        left: 50%;
        transform: translateX(-50%);
        width: 100%;
        display: flex;
        justify-content: center;
        padding: 0 20px;
    }

    .btnlist {
        display: flex;
        border: 1px solid #3772ff;
        background-color: #3772ff;
        border-radius: 12.5px;
        width: 305px;
        overflow: hidden;
    }

    .btn-item {
        flex: 1;
        padding: 12px;
        text-align: center;
        color: #fff;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.3s;
    }

    .activeBtn {
        border-radius: 12.5px 0 17.5px 12.5px;
        background-color: #fff;
        color: #000;
    }

    .activeBtn2 {
        border-radius: 0 12.5px 12.5px 17.5px;
        background-color: #fff;
        color: #000;
    }
  </style>